<?php
/**
 * @Author:      zk
 * @DateTime:    18-7-25 下午4:05
 * @Description: 审批模型审批条件分组表相关
 */

class OAApproverRuleGroup extends Eloquent
{
    protected $table = 'oa_approver_rule_group';

    /**
     * @Author:      zk
     * @DateTime:    18-7-27 下午1:20
     * @Description: 根据审批模板id获取该审批模板的各层级的审批人员及审批条件
     * @param int $approval_model_id 审批模板id
     * @param int $parent_id    审批条件分组父id
     * @return array
     */
    public static function getRuleGroupByApprovalModelId($approval_model_id, $parent_id = 0){
        $select_arr = [
            'id', 'approval_model_id', 'level', 'approval_way', 'parent_id', 'name',
        ];
        $list = OAApproverRuleGroup::where('approval_model_id', $approval_model_id)
                ->where('parent_id', $parent_id)
                ->where('status', 1)
                ->select($select_arr)
                ->get()
                ->toArray();
        if(empty($list)){
            return [];
        }
        
        $result = [];
        foreach ($list as $k => $v) {
            $temp = $v;
            //暂时固定用户类型  【 因为获取用户列表的时候，都是获取的hrm_user_id 】
            $temp['user_type'] = 2;     //用户id类型 [1:OA用户id;2:hrm平台用户id;]
            //获取人或者角色
            $people = OAApproverConfig::getApproverByRuleGroupId($v['id']);
            if(!empty($people)){
                $temp['role_ids'] = $people['role_ids'];
                $temp['user_ids'] = $people['user_ids'];
                $temp['people'] = $people['list'];
            }else{
                $temp['role_ids'] = [];
                $temp['user_ids'] = [];
                $temp['people'] = [];
            }
            
            //获取分组条件
            $temp['condition'] = OAApproverRule::getRuleByRuleGroupId($v['id']);
            
            //递归获取下一级
            $children = self::getRuleGroupByApprovalModelId($approval_model_id, $v['id']);
            $temp['children'] = $children;
//            if(!empty($children)){
//                $temp['children'] = $children;
//            }
            
            $result[] = $temp;
        }
        
        return array_values($result);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-8-1 上午10:06
     * @Description: 添加审批人、审批角色 及 审批条件
     * @param int $approval_model_id    审批模板id
     * @param int $user_id      管理员id
     * @param array $array      添加数据数组
     * @param int $parent_id    审批条件分组父id
     * @return boolean
     */
    public static function addApprover($approval_model_id, $user_id, $array, $parent_id = 0) {
        if(!is_array($array)){
            return FALSE;
        }
        foreach ($array as $k => $v) {
            //入库 审批模型审批条件分组表
            $approver_rule_group_id = OAApproverRuleGroup::insertGetId([
                'approval_model_id' => $approval_model_id,
                'level' => $v['level'],
                'approval_way' => $v['approval_way'],
                'parent_id' => $parent_id,
                'name' => $v['name'],    //审批人字符串(前端自定义name值)
                'status' => 1,
                'created_by' => $user_id,
                'created_at' => Common::num2DateTime(time()),
            ]);
            if(!$approver_rule_group_id){
                return FALSE;
            }
            
            //入库 审批模型审批人配置表
            $insert_approver_config_data = [];  //添加审批人数据
            $approver_role_ids_arr = $v['role_ids'];  //审批人角色数组
            $approver_user_ids_arr = $v['user_ids'];  //审批人用户数组
            if($v['user_type'] == 2){   //用户id类型 [1:OA用户id;2:hrm平台用户id;]
                $approver_user_ids_arr = OAUser::getUseridByHrmUserid($approver_user_ids_arr);    //hrm用户id转换成OA用户id
            }
            if(!empty($approver_role_ids_arr)){     //角色
                foreach ($approver_role_ids_arr as $_k => $_v) {
                    $temp = [
                        'approval_model_id' => $approval_model_id,
                        'type' => 2,    //类型 1:用户;2:角色;
                        'user_type' => 1,   //用户类型 1:审批人员;2:抄送人员;
                        'user_id' => 0,   //用户id
                        'role_id' => $_v,   //角色id
                        'rule_group_id' => $approver_rule_group_id, //审批条件组id
                        'status' => 1,
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];
                    $insert_approver_config_data[] = $temp;
                }
            }
            if(!empty($approver_user_ids_arr)){     //用户
                foreach ($approver_user_ids_arr as $_k => $_v) {
                    $temp = [
                        'approval_model_id' => $approval_model_id,
                        'type' => 1,    //类型 1:用户;2:角色;
                        'user_type' => 1,   //用户类型 1:审批人员;2:抄送人员;
                        'user_id' => $_v,   //用户id
                        'role_id' => 0,   //角色id
                        'rule_group_id' => $approver_rule_group_id, //审批条件组id
                        'status' => 1,
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];
                    $insert_approver_config_data[] = $temp;
                }
            }
            $res_approver = OAApproverConfig::insert($insert_approver_config_data);
            if(!$res_approver){
                return FALSE;
            }
            
            //入库 审批模型审批条件表
            if(!empty($v['condition'])){
                $insert_approver_rule_data = [];  //添加审批条件数据
                foreach ($v['condition'] as $_k2 => $_v2) {
                    $temp = [
                        'approval_model_id' => $approval_model_id,
                        'rule_group_id' => $approver_rule_group_id, //审批条件组id
                        'key_name' => $_v2['key_name'],
                        'operator' => $_v2['operator'],
                        'key_value' => $_v2['key_value'],
                        'sort' => $_v2['sort'],
                        'relation' => $_v2['relation'],
                        'status' => 1,
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];
                    $insert_approver_rule_data[] = $temp;
                }
                $res_approver_rule = OAApproverRule::insert($insert_approver_rule_data);
                if(!$res_approver_rule){
                    return FALSE;
                }
            }
            //递归创建
            if(!empty($v['children'])){
                $res = self::addApprover($approval_model_id, $user_id, $v['children'], $approver_rule_group_id);
                if(!$res){
                    return FALSE;
                }
            }
        }
        
        return TRUE;
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-8-1 下午2:10
     * @Description: 根据审批模型id和申请内容 添加审批人 到 申请流转表
     * @param int $apply_id    申请id
     * @param int $approval_model_id    审批模板id
     * @param int $user_id      管理员id
     * @param array $array      申请内容填写数组
     * @param array $notify_status_arr      各平台通知状态数组
     * $notify_status_arr = [
            'pc' => $pc,
            'wechat' => $wechat,
            'email' => $email,
        ];
     * @param int $parent_id    审批条件分组父id
     * @return boolean
     */
    public static function addApproverToflowByApprovalModelId($apply_id, $approval_model_id, $user_id, $array, $notify_status_arr, $parent_id = 0) {
        $result = FALSE;
        if(!is_array($array)){
            return $result;
        }
        $select_arr = [
            'id', 'approval_model_id', 'level', 'approval_way', 'parent_id',
        ];
        $list = OAApproverRuleGroup::where('approval_model_id', $approval_model_id)
                ->where('parent_id', $parent_id)
                ->where('status', 1)
                ->select($select_arr)
                ->get()
                ->toArray();
        if(!empty($list)){
            foreach ($list as $k => $v) {
                //获取分组条件
                $condition = OAApproverRule::getRuleByRuleGroupId($v['id']);
                $compare = FALSE;   //初始的比较结果
                if(!empty($condition)){
                    //存在条件时
                    foreach ($condition as $k_2 => $v_2) {
                        //关系(与下一条件关系 1:and;2:or;)
                        if($v_2['relation'] == 1){
                            if(isset($array[$v_2['key_name']])){
                                $check_res = self::checkCondition($v_2['operator'], $v_2['key_value'], $array[$v_2['key_name']]);
                                if($check_res){
                                    $compare = TRUE;
                                } else {
                                    $compare = FALSE;
                                    break;
                                }
                            } else {
                                $compare = FALSE;
                                break;
                            }
                        } else {
                            if(isset($array[$v_2['key_name']])){
                                $check_res = self::checkCondition($v_2['operator'], $v_2['key_value'], $array[$v_2['key_name']]);
                                if($check_res){
                                    $compare = TRUE;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    //无条件时 始终成立
                    $compare = TRUE;
                }
                
                if($compare){
                    //审批人判断成立    添加审批人
                    $people_arr = OAApproverConfig::getApproverUserInfoByRuleGroupId($v['id'], $user_id);     //获取审批人员id
                    if(empty($people_arr)){
                        return $result;
                        break;
                    }
                    $insert_data_approver_user = [];      //审批模型的审批人员添加数据
                    foreach ($people_arr as $v_3) {
                        $temp = [
                            'apply_id' => $apply_id,
                            'user_type' => 1,   //用户类型(1:审批人员;2:抄送人员;)
                            'user_id' => $v_3,
                            'level' => $v['level'], 
                            'status' => 1, //状态(1:未审批;2:已审批;3:他人已审批;4:申请人已撤回;5:审批人已转发;)
                            'approval_way' => $v['approval_way'],
                            'pc' => $notify_status_arr['pc'],
                            'wechat' => $notify_status_arr['wechat'],
                            'email' => $notify_status_arr['email'],
                            'created_by' => $user_id,
                            'created_at' => Common::num2DateTime(time()),
                        ];
                        $insert_data_approver_user[] = $temp;
                    }
                    $ins_approver_user = OAApplyFlow::insert($insert_data_approver_user);
                    if(!$ins_approver_user){
                        return $result;
                        break;
                    }
                    
                    //递归创建
                    $res = self::addApproverToflowByApprovalModelId($apply_id, $approval_model_id, $user_id, $array, $notify_status_arr, $v['id']);
                    if(!$res){
                        return $result;
                        break;
                    }
                    
                    $result = TRUE;
                }
                //  暂时注释    18-8-27 下午6:05
//                if($result){    //只走一条审批流程
//                    return $result;
//                    break;
//                }
            }
        } else {
            if($parent_id != 0){    //必须要有一级审批人
                $result = TRUE;
            }
        }
        
        return $result;
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-8-1 下午3:40
     * @Description: 校验是否满足条件
     * @param string $operator             逻辑关系 (多个值用英文逗号分隔) [1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
     * @param string $reference_value   参考值 (多个值用英文逗号分隔)
     * @param string $value 校验值
     * @return boolean true:满足条件; false:不满足条件;
     */
    public static function checkCondition($operator, $reference_value, $value){
        $result = FALSE;
        $operator_arr = explode(',', $operator);
        $operator_count = count($operator_arr);
        if($operator_count != 1){
            $reference_value_arr = explode(',', $reference_value);
            $reference_value_count = count($reference_value_arr);
            if($operator_count != $reference_value_count){
                //配置参数不对等的时候 直接返回 false
                return $result;
            }
            //表达式的前半段……  (前半段 始终与 后半段是 and 关系)
            //[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
            $result = FALSE;
            switch ($operator_arr[0]) {
                case 1:
                    if ($reference_value_arr[0] == $value) {
                        $result = TRUE;
                    }
                    break;
                case 2:
                    if ($reference_value_arr[0] != $value) {
                        $result = TRUE;
                    }
                case 3:
                    if ($value < $reference_value_arr[0]) {
                        $result = TRUE;
                    }
                    break;
                case 4:
                    if ($value > $reference_value_arr[0]) {
                        $result = TRUE;
                    }
                    break;
                case 5:
                    if ($value <= $reference_value_arr[0]) {
                        $result = TRUE;
                    }
                    break;
                case 6:
                    if ($value >= $reference_value_arr[0]) {
                        $result = TRUE;
                    }
                    break;
                default:
                    break;
            }
            if(!$result){
                return $result;
            }
            //表达式的后半段……
            //[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
            switch ($operator_arr[1]) {
                case 1:
                    if ($reference_value_arr[1] == $value) {
                        $result = TRUE;
                    } else {
                        $result = FALSE;
                    }
                    break;
                case 2:
                    if ($reference_value_arr[1] != $value) {
                        $result = TRUE;
                    } else {
                        $result = FALSE;
                    }
                case 3:
                    if ($value < $reference_value_arr[1]) {
                        $result = TRUE;
                    } else {
                        $result = FALSE;
                    }
                    break;
                case 4:
                    if ($value > $reference_value_arr[1]) {
                        $result = TRUE;
                    } else {
                        $result = FALSE;
                    }
                    break;
                case 5:
                    if ($value <= $reference_value_arr[1]) {
                        $result = TRUE;
                    } else {
                        $result = FALSE;
                    }
                    break;
                case 6:
                    if ($value >= $reference_value_arr[1]) {
                        $result = TRUE;
                    } else {
                        $result = FALSE;
                    }
                    break;
                default:
                    break;
            }
            return $result;
        } else {
            // [1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
            switch ($operator) {
                case 1:
                    if ($reference_value == $value) {
                        $result = TRUE;
                    }
                    break;
                case 2:
                    if ($reference_value != $value) {
                        $result = TRUE;
                    }
                case 3:
                    if ($value < $reference_value) {
                        $result = TRUE;
                    }
                    break;
                case 4:
                    if ($value > $reference_value) {
                        $result = TRUE;
                    }
                    break;
                case 5:
                    if ($value <= $reference_value) {
                        $result = TRUE;
                    }
                    break;
                case 6:
                    if ($value >= $reference_value) {
                        $result = TRUE;
                    }
                    break;
                case 7:
                    $value_arr = explode(',', $value);
                    $value_count = count($value_arr);
                    $reference_value_arr = explode(',', $reference_value);
                    if($value_count > 1){
                        //多选项(选了多个值) 必须所选择的多个值都在范围之内
                        $temp_arr = array_intersect($reference_value_arr, $value_arr);
                        if(count($temp_arr) == $value_count){
                            $result = TRUE;
                        }
                    } else {
                        //单选项、下拉选项、多选项(只选一个值)
                        if(in_array($value, $reference_value_arr)){
                            $result = TRUE;
                        }
                    }
                    
                    break;

                default:
                    break;
            }
        }
        
        return $result;
    }
    
}
